﻿#include "mainwidget.h"
#include "ui_mainwidget.h"
#include <QJsonDocument>
#include <QMenu>
#include <QMessageBox>
#include <QNetworkReply>
#include <QPixmap>
#include <QTimer>
#include <QUrlQuery>
#include "channelchatroom.h"
#include "clientcallback.h"
#include "confsettings.h"
#include "dispatchwidget.h"
#include "globaltools.h"
#include "httppost.h"
#include "notifylabel.h"
#include "p2pchatroom.h"
#include "protohash.h"
#include "servertimesync.h"
#include "uitools.h"

const QString webLoginParam = QLatin1String("/vc/doLoginByPc?uid=%1&password=%2&times=1&url=");

MainWidget::MainWidget(QWidget *parent) :
    QFrame(parent),
    ui(new Ui::MainWidget), login_state_(login_state_initial), webCreated(false)
{
    ui->setupUi(this);
    auto globalConf = ConfSettings::instance();
    ui->label_title->setText(globalConf->getTitleLabel());
    if(!globalConf->titleStyle.isEmpty())
        ui->label_title->setStyleSheet(globalConf->titleStyle);
    auto menu = new QMenu(ui->button_person);
    ui->button_person->setMenu(menu);
    menu->addAction(ui->action_logout);
    connect(ui->button_person, &QAbstractButton::clicked, ui->button_person, &QToolButton::showMenu);

    auto contact_view = ui->view_contact_list;
    ui->view_channel_talk->getContactUser = [contact_view](qint64 uid){
        return contact_view->findUser(uid);
    };

    ui->btn_dispatch->hide();
    //初始默认状态是选中channel_talk

    connect(ui->view_channel_talk, &ChannelItemView::deleteChannelMessage, this, &MainWidget::deleteChannelMessage);

    if(parent)
    {
        connect(ui->button_min,SIGNAL(clicked(bool)), parent, SLOT(showMinimized()));
        connect(ui->button_max, SIGNAL(clicked()), parent, SLOT(button_max_clicked()));
        connect(ui->button_close,SIGNAL(clicked(bool)), parent, SLOT(hide()));
        connect(ui->action_logout,SIGNAL(triggered(bool)), parent, SLOT(closeCentral()));
    }

    if(auto callback = ClientCallback::instance())
    {
        connect(callback, &ClientCallback::signal_local_video, this, &MainWidget::slot_local_video, Qt::QueuedConnection);
        connect(callback, &ClientCallback::signal_remote_video, this, &MainWidget::slot_remote_video, Qt::QueuedConnection);
        connect(callback, &ClientCallback::signal_local_audio, this, &MainWidget::slot_local_audio, Qt::QueuedConnection);
        connect(callback, &ClientCallback::signal_remote_audio, this, &MainWidget::slot_remote_audio, Qt::QueuedConnection);
    }
    on_stackedWidget_currentChanged();
}

MainWidget::~MainWidget()
{
    delete ui;
}

void MainWidget::setMaximizeButton(bool isMax)
{
    ui->button_max->setChecked(isMax);
}

bool MainWidget::isTitle(const QPoint &pos) const
{
    return ui->widget_topbar->rect().contains(pos);
}

void MainWidget::readyToClose()
{
    closeDynamicWithoutNew();
}

#ifdef QT_DEBUG
#include <QInputDialog>
#endif

void MainWidget::handle_trayIcon_menu(QMenu *menu)
{
#ifdef QT_DEBUG
    if(auto action = menu->addAction(QLatin1String("Open Channel")))
    {
        connect(action, &QAction::triggered, this, [this](){
            auto rid = QInputDialog::getInt(this, QLatin1String("Open Channel"), QLatin1String("Input id:"), 0, 0, INT_MAX, 1, Q_NULLPTR, Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
            if(rid > 0)
            {
                auto button = QMessageBox::question(this, QLatin1String("Question"), QLatin1String("Is P2P?"));
                if(button == QMessageBox::Yes || button == QMessageBox::No)
                {
                    auto uniqueid = BaseChannelInfo::makeUniqueId(rid, button == QMessageBox::Yes);
                    handle_open_room(uniqueid, true);
                }
            }
        });
    }
    if(auto action = menu->addAction(QLatin1String("Share Video")))
    {
        connect(action, &QAction::triggered, this, [this]() {
            auto text = QInputDialog::getText(this, QLatin1String("Share Video JSON"), QString(), QLineEdit::Normal, QString(), Q_NULLPTR, Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
            if(!text.isEmpty()) {
                auto json = QJsonDocument::fromJson(text.toUtf8());
                auto shareType = json["type"].toString();
                auto id = qint64(json["id"].toDouble());
                if(shareType == "uid") {
                    handle_open_room(BaseChannelInfo::makeUniqueId(id, true), false, true);
                } else if (shareType == "rid") {
                    if(ui->view_channel_talk->findChannel(id))
                        handle_open_room(BaseChannelInfo::makeUniqueId(id, false), false, true);
                    else {
                        QTimer::singleShot(30*1000, this, [this, id](){
                            handle_open_room(BaseChannelInfo::makeUniqueId(id, false), false, true);
                        });
                    }
                }
            }
        });
    }
#endif
}

void MainWidget::handle_open_room(qint64 uniqueId, bool closeOldEvenNoNewRoom, bool shareCommand)
{
    //1.检查是否已经打开
    if(ui->stackedWidget->isChatRoomOpen(uniqueId))
    {
        if(shareCommand)
            ui->stackedWidget->getChatRoom()->handle_share_command();
        return;
    }
    //2.创建
    auto newRoom = ui->view_channel_talk->handle_open(uniqueId);
    if(!newRoom)
    {
        //创建失败
        if(closeOldEvenNoNewRoom)
        {
            closeDynamicWithoutNew();
        }
        return;
    }
    if(auto widget = this->window())
    {
        Qt::WindowStates state = widget->windowState();
        if(state.testFlag(Qt::WindowMinimized))
            widget->setWindowState(state & (~Qt::WindowMinimized));
        if(widget->isHidden())
            widget->show();
        widget->activateWindow();
        widget->raise();
    }

    ui->stackedWidget->addChatRoom(newRoom);
    newRoom->initWith(this);
    if(shareCommand)
        newRoom->handle_share_command();
}

static const QString personFormat = QLatin1String("<html><head/><body><p>")+QObject::trECSUTF8("欢迎你")+QLatin1Literal(", <span style=\" font-size:14pt;\">%1</span></p></body></html>");

void MainWidget::handle_contact_list(const QVariant &variant)
{
    auto contact_list = ProtoArray::decodeArray(variant.toByteArray());
    ui->view_contact_list->handle_contact_list(&contact_list);
    ui->view_channel_talk->handle_contact_list();
}

void MainWidget::handle_org_list(const QVariant &variant)
{
    auto org_list = ProtoArray::decodeArray(variant.toByteArray());
}

void MainWidget::handle_login_ack(QVariantHash &msg)
{
    //cmd_param_uid/cmd_param_terminal_id/cmd_param_phone/cmd_param_imei/cmd_param_iccid
    //cmd_param_time/cmd_param_token/cmd_param_mds_info/cmd_param_msg_time
    //先取数据库
    //ui->tab_contact_list->handle_contact_list(Q_NULLPTR);
    if(auto user = ui->view_contact_list->handle_my_contact(msg))
    {
        ui->button_person->setIcon(QIcon(ContactUser::decoration(user->uid, user->getName(true), 30, 30, this->font()).value<QPixmap>()));
        ui->button_person->setToolTip(user->getToolTip());
        if(getParam(msg, cmd_param_type).toInt() == 4)  //调度员
        {
            ui->btn_dispatch->show();
            createWeb();
        }
    }
    QVariant var = getParam(msg, cmd_param_room_list);
    //if(var.isValid())
    //    ui->view_channel_talk->handle_channel_list(ProtoArray::decodeArray(var.toByteArray()));
    ui->view_channel_talk->set_user_mute_list();
    ui->view_channel_talk->set_room_mute_list();
}

void MainWidget::handle_change_state(QVariantHash &msg)
{
    login_state_ = getParam(msg, cmd_param_state).toInt();
}

void MainWidget::handle_recv_im(QVariantHash &msg)
{
    qint64 src_id = getParam(msg, cmd_param_snd_id).toLongLong();
    if(!src_id || src_id == ClientCallback::instance()->get_my_id())
        return;

    int type = getParam(msg, cmd_param_msg_type).toInt();
    if(type == msg_type_ptt_req)
    {
        ClientCallback::instance()->im_send_msg(src_id, QString(), msg_type_ptt_ack, QObject::trECSUTF8("对方在线，您可以进行对讲！"), getParam(msg, cmd_param_time_len).toLongLong());
    }
    else if(type == msg_type_ask_online)
    {
        //回复在线
        ClientCallback::instance()->im_send_msg(src_id, "", msg_type_ask_online_ack, "");
    }
    else if(type == msg_type_dispatch_req)
    {
        qint64 cur_time = ServerTimeSync::instance()->getServerTime();
        if(cur_time - getParam(msg, cmd_param_msg_time).toLongLong() > 15 * 1000)
            return;
        //PC版不接受调度
        ClientCallback::instance()->im_send_msg(src_id, "", msg_type_dispatch_reject, "");
        return;
    }
    else if (type == msg_type_share_video)
    {
        qint64 cur_time = ServerTimeSync::instance()->getServerTime();
        if(cur_time - getParam(msg, cmd_param_msg_time).toLongLong() > 15 * 1000)
            return;
        auto json = QJsonDocument::fromJson(getParam(msg, cmd_param_msg).toByteArray());
        if(!json.isNull())
        {
            auto id = qint64(json["id"].toDouble());
            if(id > 0)
            {
                auto shareType = json["type"].toString();
                if(shareType == "uid") {
                    handle_open_room(BaseChannelInfo::makeUniqueId(id, true), false, true);
                } else if (shareType == "rid") {
                    //临时频道刷新有延迟，推迟1秒处理
                    QTimer::singleShot(1000, this, [this, id](){
                        if(ui->view_channel_talk->findChannel(id))
                            handle_open_room(BaseChannelInfo::makeUniqueId(id, false), false, true);
                        else    //还找不到频道，30秒后再试一次
                            QTimer::singleShot(30*1000, this, [this, id](){
                                handle_open_room(BaseChannelInfo::makeUniqueId(id, false), false, true);
                            });
                    });
                }
            }
        }
        return;
    }
    else if(ui->view_channel_talk->preprocess_p2p_msg(src_id, type, msg))
    {
        auto dynamic = ui->stackedWidget->getDynamicWidget();
        //先处理大界面
        bool isRead = false;
        if(auto dispatch = qobject_cast<DispatchWidget*>(dynamic))
        {
            dispatch->handle_im_msg(type, src_id, msg);
        }
        else if(auto chatroom = qobject_cast<P2PChatRoom*>(dynamic))
        {
            if(chatroom->getId() == src_id)
            {
                chatroom->handle_msg(type, msg);
                isRead = true;
            }
        }
        //再处理数据列表
        if(BaseChannelInfo::isVisibleMsg(msg, false))
            ui->view_channel_talk->handle_p2p_msg(src_id, msg, isRead);
    }
}

void MainWidget::handle_im_event(int cmd_type, QVariantHash &msg)
{
    if(cmd_type == cmd_type_ntfy_data)
    {
        QVariant var = getParam(msg, cmd_param_contact_list);
        if(var.isValid())
            handle_contact_list(var);
        var = getParam(msg, cmd_param_orgnization_list);
        if(var.isValid())
            handle_org_list(var);
        var = getParam(msg, cmd_param_msg_list);
        if(var.isValid())
        {
            auto msg_list = ProtoArray::decodeArray(var.toByteArray());
            if(!msg_list.isEmpty())
            {
                std::sort(msg_list.begin(), msg_list.end(), ChannelInfo::msg_less_than);
                
                const auto myid = ClientCallback::instance()->get_my_id();

                auto dynamic = ui->stackedWidget->getDynamicWidget();
                auto dispatch = qobject_cast<DispatchWidget*>(dynamic);
                auto chatroom = qobject_cast<P2PChatRoom*>(dynamic);

                QVariantHash emptyHash; //用于先append再swap
                QMap<qint64, QList<QVariantHash>> msg_map;
                QPair<qint64, QByteArrayList> mark_mids;

                for (auto it = msg_list.begin(); it != msg_list.end(); it++) {
                    auto &msg = *it;
                    auto snd_id = getParam(msg, cmd_param_snd_id).toLongLong();
                    auto rcv_id = getParam(msg, cmd_param_rcv_id).toLongLong();
                    auto uid = getParam(msg, cmd_param_uid).toLongLong();
                    QByteArray mid = getParam(msg, cmd_param_mid).toByteArray();
                    if(mid.isEmpty())
                        continue;
                    if(snd_id <= 0 || rcv_id <= 0 || snd_id == rcv_id || (snd_id != myid && rcv_id != myid))
                    {
                        //im msg list参数略有不同，需要转一下
                        bool ok = false;
                        auto dir = getParam(msg, cmd_param_direction).toInt(&ok);
                        if(!ok)
                            continue;
                        if(uid <= 0)
                            continue;
                        if(dir == msg_dir_send)
                        {
                            setParam(msg, cmd_param_snd_id, myid);
                            setParam(msg, cmd_param_rcv_id, uid);
                        }
                        else if(dir == msg_dir_recv)
                        {
                            setParam(msg, cmd_param_snd_id, uid);
                            setParam(msg, cmd_param_rcv_id, myid);
                        }
                        else
                            continue;
                        //已有direction数据，add时不用再加
                    }
                    else if(snd_id == myid)
                    {
                        uid = rcv_id;
                        setParam(msg, cmd_param_direction, msg_dir_send);
                    }
                    else
                    {
                        uid = snd_id;
                        setParam(msg, cmd_param_direction, msg_dir_recv);
                    }
                    if(uid <= 0)
                        continue;
                    auto type = getParam(msg, cmd_param_msg_type).toInt();
                    if(dispatch)
                        dispatch->handle_im_msg(type, uid, msg);
                    else if (chatroom && chatroom->getId() == uid) {
                        chatroom->handle_msg(type, msg);
                        if(BaseChannelInfo::isUnreadMsg(type, msg))
                        {
                            setParam(msg, cmd_param_state, msg_state_readed);
                            if(mark_mids.second.isEmpty())
                                mark_mids.first = uid;
                            mark_mids.second.append(mid);
                        }
                    }
                    //把这条信息移到map
                    auto & list = msg_map[uid];
                    list.append(emptyHash);
                    list.last().swap(msg);
                }
                for (auto it = msg_map.begin(); it != msg_map.end(); it++) {
                    ui->view_channel_talk->handle_p2p_msg_list(it.key(), it.value());
                }
                if(!mark_mids.second.isEmpty())//如果为空，uid没有设置
                    P2PChanneInfo::call_mark_read_all(mark_mids.first, mark_mids.second);
            }
        }
    }
    else if(cmd_type == cmd_type_send_msg)
        handle_recv_im(msg);
    else if(cmd_type == cmd_type_ack)
    {
        int req_cmd = getParam(msg, cmd_param_ack_cmd).toInt();
        if(req_cmd == cmd_type_send_msg)
        {
            int code = getParam(msg, cmd_param_code).toInt();
            auto rcv_id = getParam(msg, cmd_param_rcv_id).toLongLong();
            auto type = getParam(msg, cmd_param_msg_type).toInt();
            if(rcv_id > 0 && type != msg_type_ask_online_ack && type != msg_type_msg_readed)
            {
                if(code == error_none)
                {
                    setParam(msg, cmd_param_state, msg_state_send_succ);
                    ui->view_channel_talk->handle_p2p_msg(rcv_id, msg, false);
                }
                else {
                    setParam(msg, cmd_param_state, msg_state_send_fail);
                    //TODO:发送失败的处理
                }
            }
        }
    }
}

void MainWidget::handle_channel_event(int cmd_type, QVariantHash &msg)
{    
    auto chatroom = qobject_cast<ChannelChatRoom*>(ui->stackedWidget->getDynamicWidget());

    if(cmd_type == cmd_type_ntfy_data)
    {
        QVariant var = getParam(msg, cmd_param_room_list);
        if(var.isValid())
            ui->view_channel_talk->handle_channel_list(ProtoArray::decodeArray(var.toByteArray()));
        var = getParam(msg, cmd_param_msg_list);
        if(var.isValid())
        {
            auto msg_list = ProtoArray::decodeArray(var.toByteArray());
            if(!msg_list.isEmpty())
            {
                std::sort(msg_list.begin(), msg_list.end(), ChannelInfo::msg_less_than);

                QMap<qint64, QList<QVariantHash>> msg_map;
                QPair<qint64, QByteArrayList> mark_mids;

                for (auto it = msg_list.begin(); it != msg_list.end(); it++)
                {
                    auto &msg = *it;
                    auto rid = getParam(msg, cmd_param_rid).toLongLong();
                    if(rid <= 0)
                        continue;
                    QByteArray mid = getParam(msg, cmd_param_mid).toByteArray();
                    if(mid.isEmpty())
                        continue;
                    if (chatroom && chatroom->getId() == rid)
                    {
                        auto type = getParam(msg, cmd_param_msg_type).toInt();
                        chatroom->handle_msg(type, msg);
                        if(BaseChannelInfo::isUnreadMsg(type, msg))
                        {
                            setParam(msg, cmd_param_state, msg_state_readed);
                            if(mark_mids.second.isEmpty())
                                mark_mids.first = rid;
                            mark_mids.second.append(mid);
                        }
                    }
                    //把这条信息移到map
                    auto & list = msg_map[rid];
                    list.append(QVariantHash());
                    list.last().swap(msg);
                }
                for (auto it = msg_map.begin(); it != msg_map.end(); it++) {
                    ui->view_channel_talk->handle_channel_msg_list(it.key(), it.value());
                }
                if(!mark_mids.second.isEmpty())
                    ChannelInfo::call_mark_read_all(mark_mids.first, mark_mids.second);
            }
        }
        return;
    }

    qint64 rid = getParam(msg, cmd_param_rid).toLongLong();

    if(cmd_type == cmd_type_login_room)
    {
        ui->view_channel_talk->handle_login_ack(rid, msg);
        return;
    }

    const bool isChannelOpen = chatroom && chatroom->getId() == rid;
    QList<QVariantHash> append_msg_list;

    if(cmd_type == cmd_type_ntfy_join || cmd_type == cmd_type_ntfy_exit)
    {
        ui->view_channel_talk->handle_join_or_exit(cmd_type, rid, msg);
    }
    else if(cmd_type == cmd_type_ntfy_mic_state)
    {
        append_msg_list.append(ui->view_channel_talk->handle_mic_state(rid, msg));
    }
    else if(cmd_type == cmd_type_room_msg)
    {
        ui->view_channel_talk->handle_channel_msg(rid, msg, isChannelOpen);
    }
    else if(cmd_type == cmd_type_sync_room)
    {
        ui->view_channel_talk->handle_basic_info(rid, msg);
        handle_channel_event(cmd_type_ntfy_mic_state, msg);
    }
    else if(cmd_type == cmd_type_ack)
    {
        int req_cmd = getParam(msg, cmd_param_ack_cmd).toInt();
        if(req_cmd == cmd_type_login_room)
        {
            ui->view_channel_talk->handle_login_ack(rid, msg);
            return;
        }
        if(req_cmd == cmd_type_apply_mic)
        {
            int code = getParam(msg, cmd_param_code).toInt();
            append_msg_list.append(ui->view_channel_talk->handle_mic_ack(rid, code, QObject::trECSUTF8("申请")));
            handle_channel_event(cmd_type_ntfy_mic_state, msg);
        }
        else if(req_cmd == cmd_type_free_mic)
        {
            int code = getParam(msg, cmd_param_code).toInt();
            append_msg_list.append(ui->view_channel_talk->handle_mic_ack(rid, code, QObject::trECSUTF8("释放")));
            handle_channel_event(cmd_type_ntfy_mic_state, msg);
        }
        else if(req_cmd == cmd_type_room_msg)
        {
            //用来标记发送信息的状态，目前不处理
            int code = getParam(msg, cmd_param_code).toInt();
            if(code == error_none)
            {
                ui->view_channel_talk->handle_channel_msg(rid, msg, false);
            }
        }
    }

    if(isChannelOpen)
    {
        if(auto channel_info = ui->view_channel_talk->findChannel(rid))
            chatroom->handle_channel_event(cmd_type, msg, *channel_info);
        if(!append_msg_list.isEmpty())
            chatroom->handle_msg_list(append_msg_list);
    }
}

void MainWidget::resizeEvent(QResizeEvent *e)
{
    QFrame::resizeEvent(e);
}

void MainWidget::button_close_clicked()
{
    if(confirm(QObject::trECSUTF8("确认"), QObject::trECSUTF8("是否确认登出?"), this))
        ui->action_logout->trigger();
}

void MainWidget::deleteChannelMessage(qint64 uniqueId)
{
    auto info = BaseChannelInfo::fromUniqueId(uniqueId);
    if(info.first)
    {
        //P2P
        ui->view_channel_talk->delete_p2p_message(info.second);
        ClientCallback::instance()->im_delete_msg(info.second);
    }
    else
    {
        //Channel
        ui->view_channel_talk->delete_room_message(info.second);
        ClientCallback::instance()->channel_delete_msg(info.second);
    }
    if(!qobject_cast<ChatRoom*>(sender()))
    {
        //不是slot
        if(auto chatroom = ui->stackedWidget->getChatRoom())
            if(chatroom->getUniqueId() == uniqueId)
                chatroom->clearMessage();
    }
}

void MainWidget::showContact()
{
    if(!ui->btn_contact_list->isChecked())
        ui->btn_contact_list->click();
}

void MainWidget::slot_local_video(qint64 room_id, qint64 user_id, QPixmap pix)
{
    //调度不显示自己，所以不处理local
    if(auto chatroom = ui->stackedWidget->getChatRoom())
        if(chatroom->getRid() == room_id)
            chatroom->handle_local_video(user_id, pix);
}

void MainWidget::slot_remote_video(qint64 room_id, qint64 user_id, QPixmap pix)
{
    auto dynamic = ui->stackedWidget->getDynamicWidget();
    if(auto chatroom = qobject_cast<ChatRoom*>(dynamic))
    {
        if(chatroom->getRid() == room_id)
            chatroom->handle_remote_video(user_id, pix);
        return;
    }
    if(auto dispatch = qobject_cast<DispatchWidget*>(dynamic))
    {
        if(room_id == P2PChanneInfo::p2pchannel_room_id)
            dispatch->handle_remote_video(user_id, pix);
    }
}

void MainWidget::slot_local_audio(qint64 room_id, qint64 user_id, int volume)
{
    //调度不显示自己，所以不处理local
    if(auto chatroom = ui->stackedWidget->getChatRoom())
        if(chatroom && chatroom->getRid() == room_id)
            chatroom->handle_audio_volume(user_id, volume);
}

void MainWidget::slot_remote_audio(qint64 room_id, qint64 user_id, int volume)
{
    auto dynamic = ui->stackedWidget->getDynamicWidget();
    if(auto chatroom = qobject_cast<ChatRoom*>(dynamic))
    {
        if(chatroom->getRid() == room_id)
            chatroom->handle_audio_volume(user_id, volume);
        return;
    }
    if(auto dispatch = qobject_cast<DispatchWidget*>(dynamic))
    {
        if(room_id == P2PChanneInfo::p2pchannel_room_id)
            dispatch->handle_audio_volume(user_id, volume);
    }
}

void MainWidget::on_btn_channel_talk_clicked(bool checked)
{
    if(checked)
    {
        ui->tabWidget->setCurrentWidget(ui->tab_channel_talk);
        ui->tabWidget->show();
        ui->btn_contact_list->setChecked(false);
    }
    else
    {
        ui->tabWidget->hide();
    }
}

void MainWidget::on_btn_contact_list_clicked(bool checked)
{
    if(checked)
    {
        ui->tabWidget->setCurrentWidget(ui->tab_contact_list);
        ui->tabWidget->show();
        ui->btn_channel_talk->setChecked(false);
    }
    else
    {
        ui->tabWidget->hide();
    }
}

void MainWidget::on_btn_dispatch_clicked()
{
    //打开调度页
    if(ui->stackedWidget->isDispatchOpen())
        return;
    auto dispatch = new DispatchWidget(ui->stackedWidget);
    ui->stackedWidget->addDispatch(dispatch);
    connect(dispatch, &DispatchWidget::showContact, this, &MainWidget::showContact);
}

void MainWidget::on_view_channel_talk_doubleClicked(const QModelIndex &index)
{
    if(QApplication::closingDown())
        return;
    if(auto info = BaseChannelInfo::fromInternalId(index.internalId()))
    {
        handle_open_room(info->uniqueId(), true);
    }
}

void MainWidget::on_view_contact_list_itemDoubleClicked(QTreeWidgetItem *item, int column)
{
    if(QApplication::closingDown())
        return;
    auto uid = item->data(0, Qt::UserRole).toLongLong();
    if(uid > 0 && uid != ClientCallback::instance()->get_my_id())
    {
        handle_open_room(BaseChannelInfo::makeUniqueId(uid, true), true);
    }
}

void MainWidget::on_button_stacked_close_clicked()
{
    //关闭当前页
    if(ui->stackedWidget->closeCurrent())
        ClientCallback::instance()->set_video_list(QSet<qint64>());
}

void MainWidget::on_stackedWidget_currentChanged()
{
    //当前页变化后
    ui->label_stacked_title->setText(ui->stackedWidget->currentTitle());
    QAbstractButton* button = Q_NULLPTR;
    bool showTitle = false;
    bool dragContact = false;
    if(ui->stackedWidget->isWeb())
    {
        button = ui->stackedWidget->currentButton();
        showTitle = button;
    }
    else if(ui->stackedWidget->isBlank())
    {
        //do nothing
    }
    else if(auto current = ui->stackedWidget->getDynamicWidget())
    {
        if(qobject_cast<DispatchWidget*>(current))
        {
            button = ui->btn_dispatch;
            showTitle = true;
            dragContact = true;
        }
        else if(qobject_cast<ChatRoom*>(current))
            showTitle = true;
    }
    ui->widget_stacked_topbar->setVisible(showTitle);
    if(button)
        button->setChecked(true);
    else if((button = ui->buttonGroup->checkedButton()))
    {
        ui->buttonGroup->removeButton(button);
        button->setChecked(false);
        ui->buttonGroup->addButton(button);
    }
    ui->view_contact_list->setDragEnabled(dragContact);
}

void MainWidget::closeDynamicWithoutNew()
{
    if(ui->stackedWidget->closeDynamic())
        ClientCallback::instance()->set_video_list(QSet<qint64>());
}

void MainWidget::handle_call_room(qint64 rid, uchar times)
{
    if(ui->view_channel_talk->hasChannel(rid))
        handle_open_room(BaseChannelInfo::makeUniqueId(rid, false), false);
    else if(times < 10) {
        QTimer::singleShot(times < 3 ? 1000 : 5 * 1000, this, [this, rid, times](){
            handle_call_room(rid, times + 1);
        });
    }
}

void MainWidget::createWeb()
{
    if(webCreated)
        return;
    auto globalConf = ConfSettings::instance();
    if(!globalConf->appDomain.isEmpty() && !globalConf->webButtons.isEmpty())
    {
        webCreated = true;
        ui->stackedWidget->createWeb();
        int tabIndex = 3;
        bool defaultSet = false;
        const kkim_login_param& param = ClientCallback::instance()->get_login_param();

        for(const auto &hash : globalConf->webButtons)
        {
            QString name = QCoreApplication::translate("ConfSettings", hash.value("name").toUtf8());
            if(name.isEmpty())
                continue;
            QString normal = hash.value("normal");
            QString hover = hash.value("hover");
            if(normal.isEmpty() || hover.isEmpty())
                continue;
            QIcon icon;
            QPixmap pixmap1(normal);
            if(pixmap1.isNull())
                continue;
            QPixmap pixmap2(hover);
            if(pixmap2.isNull())
                continue;
            icon.addPixmap(pixmap1, QIcon::Normal, QIcon::Off);
            icon.addPixmap(pixmap2, QIcon::Normal, QIcon::On);
            QUrl url(globalConf->appDomain + webLoginParam.arg(param.uid).arg(QString::fromLatin1(param.hashed_password.toHex())) + QUrl::toPercentEncoding(hash.value("url")));
            auto button = new QToolButton(ui->widget);
            button->setIcon(icon);
            button->setIconSize(pixmap1.size());
            button->setToolButtonStyle(Qt::ToolButtonIconOnly);
            button->setAutoRaise(true);
            button->setCheckable(true);
            button->setAutoExclusive(true);
            button->setToolTip(name);
            ui->buttonGroup->addButton(button);
            ui->verticalLayout_2->insertWidget(tabIndex++, button);
            connect(button, &QToolButton::clicked, this, [this, button, url](){
                ui->stackedWidget->showWeb(button, url);
            });
            if(!defaultSet && hash.value("default")=="true")
            {
                defaultSet = true;
                button->click();
            }
        }
    }
}

qint64 MainWidget::openedUniqueId()
{
    if(auto chatroom = ui->stackedWidget->getChatRoom())
        return chatroom->getUniqueId();
    return 0;
}

void MainWidget::on_edit_search_channel_returnPressed()
{
    QString keyword = ui->edit_search_channel->text();
    ui->view_channel_talk->handle_search(keyword);
    if(keyword.isEmpty())
        ui->edit_search_channel->setPlaceholderText(trECSUTF8("搜索"));
    else
        ui->edit_search_channel->setPlaceholderText(trECSUTF8("正在显示搜索: ") + keyword);
}

void MainWidget::on_edit_search_contact_returnPressed()
{
    QString keyword = ui->edit_search_contact->text();
    ui->view_contact_list->handle_search(keyword);
    if(keyword.isEmpty())
        ui->edit_search_contact->setPlaceholderText(trECSUTF8("搜索"));
    else
        ui->edit_search_contact->setPlaceholderText(trECSUTF8("正在显示搜索: ") + keyword);
}
